package br.com.lordpetstore.mb;

import java.io.Serializable;

import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

import br.com.gaspar.utils.exception.BaseException;
import br.com.lordpetstore.bo.iface.IProjetoBO;
import br.com.lordpetstore.modelo.Usuario;

@ManagedBean(name="LoginMB")
@SessionScoped
public class LoginMB implements Serializable {
	
	private String usuario;
	
	private String senha;
	
	@EJB
	private IProjetoBO<Usuario> bo;
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	public String login() {
		FacesContext fc = FacesContext.getCurrentInstance();
		
		Usuario usu = null;
		try {
			usu = bo.buscarPorNamedQuery("Usuario.buscarPorNome", getUsuario());
		} catch (BaseException e) {
			e.printStackTrace();
		}
		
		if (usu != null && usu.getSenha().equals(getSenha())) {
			ExternalContext ec = fc. getExternalContext();
			HttpSession session = (HttpSession)ec.getSession(false);
			session.setAttribute("usuarioLogado", this.usuario);
		
			return "/socio/crud.jsf";
		 } else {
			 FacesContext.getCurrentInstance().addMessage(null,
						new FacesMessage(FacesMessage.SEVERITY_ERROR, "usuário e/ou senha inválidos", "usuário e/ou senha inválidos"));
			 
		 return "/login/login.jsf";
		 }
	}
		
	public String logout() {
		FacesContext fc = FacesContext.getCurrentInstance();
		ExternalContext ec = fc.getExternalContext();
		HttpSession session = (HttpSession)ec.getSession(false);
		session.removeAttribute("usuario");
		session.invalidate();
		
		return "/login/login.jsf";
	}
	
	public String getUsuario() {
		return usuario;
	}

	public void setUsuario(String usuario) {
		this.usuario = usuario;
	}

	public String getSenha() {
		return senha;
	}

	public void setSenha(String senha) {
		this.senha = senha;
	}
}
